package com.macrog.rabbitmq.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;

/**
 * Created by Administrator on 2018/9/1.
 */
public class ConnectionFactoryUtil {

    private static final ConnectionFactory factory;

    static {
        factory = new ConnectionFactory();
        factory.setHost("192.168.31.227");
        factory.setVirtualHost("/macrog");
        factory.setUsername("macrog");
        factory.setPassword("macrog");
        System.out.println("ConnectionFactory创建成功");
    }

    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = factory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection, Channel channel) {
        if (channel != null) {
            try {
                channel.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                channel = null;
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection = null;
            }
        }
    }
}
